package kr.co.kiso.pub.bd.ma.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.kiso.usr.bd.ma.service.BDMAService;
import kr.co.kiso.usr.bd.ma.vo.BDMAVo;
import kr.co.kiso.usr.common.BaseController;
import kr.co.kiso.usr.common.vo.CommonVo;
import kr.co.kiso.usr.utils.PaginationInfo;
import kr.co.kiso.usr.utils.ToJinsu;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("pub/bd/ma/*")
public class PBDMAController extends BaseController{
	@Autowired
	private BDMAService bdmaService;

	private final String FILE_PATH= "/bd/ma";

	Logger log = Logger.getLogger(getClass());
	
	/**
	 * 반환할 jsp 파일 정의
	 * @param vo
	 * @return
	 */
	public ModelAndView getJspFile(BDMAVo vo, HttpServletRequest req){
		ModelAndView mav = new ModelAndView();
		StringBuffer jspFile= new StringBuffer();
		
		if(vo.getBrd_type().equals("ABC")
				||
				vo.getBrd_type().equals("")
				){
			return mav;
		}else{
			//게시판
			String url = req.getServletPath();
			
			url = url.replaceAll(".do", "");
			
			String[] urlSplit = url.split("/");
			
			for(int i=2; i<= urlSplit.length ;i++){
				if(i==urlSplit.length){
					jspFile.append("/");
					jspFile.append(vo.getBrd_type());
					jspFile.append("/");
					jspFile.append(urlSplit[i-1]);
				}else{
					jspFile.append("/");
					jspFile.append(urlSplit[i-1]);
				}
			}
		}
		mav = new ModelAndView(jspFile.toString());
		return mav;
	}
	
	/**
	 * 게시판 조회
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma010Q(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = getJspFile(vo,req);
		
		if(vo.getSrc_content()!=null && !vo.getSrc_content().equals("")){
			vo.setSrc_content("%"+vo.getSrc_content()+"%");
		}
		if(vo.getSrc_reg_dt() !=null && !vo.getSrc_reg_dt().equals("")){
			vo.setSrc_reg_dt("%"+vo.getSrc_reg_dt()+"%");
		}
		if(vo.getSrc_reg_nm()!=null && !vo.getSrc_reg_nm().equals("")){
			vo.setSrc_reg_nm("%"+vo.getSrc_reg_nm()+"%");
		}
		
		vo.setView_status("N");
		
		// 페이징 시작
		PaginationInfo paginationInfo = new PaginationInfo();
		int currnetPageNo = vo.getCurrentPageNo() <= 1 ? 1 : (Integer) vo
				.getCurrentPageNo();
		vo.setCurrentPageNo(currnetPageNo);
		vo.setParamMap(requestPram2Map(req));
//		if (vo.getSch_title() != null && !vo.getSch_title().equals("")) {
//			vo.setSch_title("%" + vo.getSch_title() + "%");
//		}
		int iTotalCnt = bdmaService.bdma010Q_cnt(vo);
		vo.setTotalRecordCount(iTotalCnt);
		
		mav.addObject("noticeList", bdmaService.bdma011Q(vo));
		
		if(iTotalCnt>0){
			// 상위 코드목록
			mav.addObject("list", bdmaService.bdma010Q(vo));
			
			mav.addObject("pageHtml", vo.getToPubHtml("./bdma010Q.do"));
			mav.addObject("paginationInfo", vo);
		}

		return mav;
	}
	
	/**
	 * 게시판 등록 수정 폼 페이지
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma020Q(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = getJspFile(vo,req);


		return mav;
	}
	
	/**
	 * 게시판 등록 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma020T(BDMAVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
		
		int seq_no = bdmaService.bdma020T(vo);
		
		ModelAndView mav = new ModelAndView("redirect:./bdma050Q.do?brd_type="+vo.getBrd_type()+"&brd_seq_no="+seq_no+"&currentPageNo="+vo.getCurrentPageNo());
		return mav; 
	}
	
	
	/**
	 * 게시판 수정 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma030t(CommonVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = new ModelAndView();


		return mav;
	}
	
	/**
	 * 게시판 삭제 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma040t(BDMAVo vo, HttpServletRequest req) throws Exception {
		ModelAndView mav=null;
		vo.setBrd_seq_no(Long.parseLong(vo.getDel_seq()[0]) );
		
//		vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
		
		Map map1 = bdmaService.bdma053Q(vo);
		if(map1 !=null){
//			List delList = new ArrayList();
//			for(int i = 0; i < vo.getDel_seq().length; i++){
//				delList.add(vo.getDel_seq()[i]);
//			}
//			vo.setDel_list(delList);
//			
//			//기존 파일 삭제
//			List delListFile = bdmaService.bdma040Q(vo);
//			for(int i=0;i<delListFile.size();i++){
//				Map map = (Map) delListFile.get(i);
//				if(map.get("M_FILE_NM")!=null){
//					File delFile = new File(req.getSession().getServletContext().getRealPath("")+(String)map.get("M_FILE_NM"));
//					if(delFile.isFile()){
//						delFile.delete();
//					}	
//				}
//			}
//			
//			bdmaService.bdma041t(vo);
//			bdmaService.bdma042t(vo);
//			bdmaService.bdma043t(vo);
//			
//			mav = new ModelAndView("redirect:./bdma010Q.do?brd_type="+vo.getBrd_type()+"&msg=삭제되었습니다");
			bdmaService.bdma090T(vo);
			mav = new ModelAndView("redirect:./bdma010Q.do?brd_type="+vo.getBrd_type()+"&msg=삭제되었습니다");
		}else{
			mav = new ModelAndView("redirect:./bdma050Q.do?brd_type="+vo.getBrd_type()+"&brd_seq_no="+vo.getBrd_seq_no()+"&currentPageNo=1&msg=비밀번호가 틀립니다."); 
		}
		
				
		
		return mav;
	}
	
	/**
	 * 게시판글 상세조회
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma050Q(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = getJspFile(vo,req);
		
		mav.addObject("map",bdmaService.bdma050Q(vo));
		mav.addObject("fileList",bdmaService.bdma051Q(vo));
		mav.addObject("fileList",bdmaService.bdma051Q(vo));
//		mav.addObject("nextInfo", bdmaService.bdma052Q(vo));

		List nextList =  bdmaService.bdma052Q(vo);
		if(nextList!=null && nextList.size()>0){
			for(int i=0; i< nextList.size();i++){
				Map next = (Map) nextList.get(i);
				if("1".equals(String.valueOf( next.get("TYPE")))){
//					이전
					mav.addObject("nextInfo1", next);	
				}else{
//					다음
					mav.addObject("nextInfo2", next);
				}
				
			}
		}

		return mav;
	}

	/**
	 * 수정화면
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma060Q(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = getJspFile(vo,req);
		
		
//		vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
		
		Map map = bdmaService.bdma053Q(vo);
		if(map !=null){
			mav.addObject("map",map);
			mav.addObject("fileList",bdmaService.bdma051Q(vo));
		}

		return mav;
	}
	
	/**
	 * 게시판 수정 프로세스
	 * @param req
	 * @param res
	 * @param mRqst
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma060T(BDMAVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView("redirect:./bdma050Q.do?brd_type="+vo.getBrd_type()+"&brd_seq_no="+vo.getBrd_seq_no()+"&currentPageNo="+vo.getCurrentPageNo());
					

		String brd_pwd = vo.getBrd_pwd();
		vo.setBrd_pwd(vo.getBrd_pwd_chk());
		
		
//		vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
		
		Map map = bdmaService.bdma053Q(vo);
		
		if(map!=null){
			vo.setBrd_pwd(brd_pwd);
			
//			vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
			//게시판 수정
			bdmaService.bdma061T(vo);
		}
		
		return mav; 
	}
	
	/**
	 * 답글 기능
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma070Q(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = getJspFile(vo,req);
		
		mav.addObject("map",bdmaService.bdma054Q(vo));

		return mav;
	}
	
	/**
	 * 답글 프로세스 
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView bdma070T(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = new ModelAndView("redirect:./bdma010Q.do?brd_type="+vo.getBrd_type()+"&currentPageNo="+vo.getCurrentPageNo());
		vo.setBrd_depth(vo.getBrd_depth()+"_");
		Map map = bdmaService.bdma071Q(vo);
		String brdDepth = (String)map.get("BRDDEPTH");
		vo.setBrd_seq_no(Long.parseLong(String.valueOf(map.get("MAXNUM"))));
		if(brdDepth==null || brdDepth.equals("")){
			vo.setBrd_depth(vo.getBrd_depth().replaceAll("_", "z"));
		}else{
			ToJinsu jinsu = new ToJinsu();
			String num = brdDepth.substring( brdDepth.length()-1,brdDepth.length());
			int iNum = Integer.parseInt( jinsu.jinsuToDec(num));
			iNum--;
			
			vo.setBrd_depth(vo.getBrd_depth().replaceAll("_", "")+jinsu.getJinsu(Integer.toString(iNum) ));
			
		}
//		vo.setBrd_pwd(secu.Enc("BRD","BRD_PWD",vo.getBrd_pwd()));
		bdmaService.bdma071T(vo);

		return mav;
	}
	
	
	@RequestMapping
	public ModelAndView bdma080T(BDMAVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = new ModelAndView("/common/toJson");
		
		bdmaService.bdma080T(vo);
		
		return mav;
	}
	
}
